package redis

import (
	"time"
)

//全局redis
var m Redis = make(map[string]interface{})

var m_time map[string]time.Time = make(map[string]time.Time)

func Keys() []string {
	return (&m).Keys()
}
func Has(key string) bool {
	return (&m).Has(key)
}

func Set(key string, value interface{}, ds int) {
	m[key] = value
	if ds == 0 {
		return
	}
	now := time.Now()
	m_time[key] = now.Add(time.Duration(ds))
	go func() {
		t := time.NewTimer(time.Second * time.Duration(ds))
		defer t.Stop()
		for {
			select {
			case <-t.C:
				delete(m, key)
				delete(m_time, key)
				return
			}
		}
	}()
}

func Get(key string) interface{} {
	return m[key]
}
func GetTime(key string) uint32 {
	if !Has(key) {
		return 0
	}
	now := time.Now()
	return uint32(m_time[key].Sub(now).Seconds())
}

func Clear() {
	for _, key := range Keys() {
		delete(m, key)
		delete(m_time, key)
	}

}

//自定义

type Redis map[string]interface{}

func NewRedis() *Redis {
	r := make(Redis)
	return &r
}
func (r *Redis) Keys() []string {
	var res = make([]string, 20)
	for key := range *r {
		res = append(res, key)
	}
	return res
}

func (r *Redis) Has(key string) bool {
	_, ok := (*r)[key]
	return ok
}
func (r *Redis) Set(key string, value interface{}, ds int) {
	(*r)[key] = value
	if ds == 0 {
		return
	}
	now := time.Now()
	m_time["myRedis-"+key] = now.Add(time.Duration(ds))
	go func() {
		t := time.NewTimer(time.Second * time.Duration(ds))
		defer t.Stop()
		for {
			select {
			case <-t.C:
				delete((*r), key)
				delete(m_time, "myRedis-"+key)
				return
			}
		}
	}()
}

func (r *Redis) Get(key string) interface{} {
	return (*r)[key]
}

func (r *Redis) GetTime(key string) uint32 {
	if !r.Has(key) {
		return 0
	}
	now := time.Now()
	return uint32(m_time["myRedis-"+key].Sub(now).Seconds())
}

func (r *Redis) Clear() {
	for _, key := range r.Keys() {
		delete(*r, key)
		delete(m_time, "myRedis-"+key)
	}

}
